package cn.j2ee.chapter2.web.model.editor;

import java.beans.PropertyEditorSupport;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebBindingInitializer;

import cn.j2ee.chapter2.web.model.PhoneNumberModel;

/**
 * 
 * 2016年11月3日下午10:56:08
 */
public class PhoneNumberEditor extends PropertyEditorSupport {
	Pattern pattern = Pattern.compile("^(\\d{3,4})-(\\d{7,8})$");

	@Override
	public String getAsText() {
		PhoneNumberModel phoneNumberModel = (PhoneNumberModel) getValue();
		WebBindingInitializer a;
		return phoneNumberModel == null ? "" : phoneNumberModel.getAreaCode() + "-" + phoneNumberModel.getPhoneNumber();
	}

	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		if (text == null || !StringUtils.hasLength(text)) {
			setValue(null);
		}
		Matcher matcher = pattern.matcher(text);
		if (matcher.matches()) {
			PhoneNumberModel phoneNumberModel = new PhoneNumberModel();
			phoneNumberModel.setAreaCode(matcher.group(1));
			phoneNumberModel.setPhoneNumber(matcher.group(2));
			setValue(phoneNumberModel);
		} else {
			throw new IllegalArgumentException(String.format("类型转换失败，需要格式[010-12345678]，但格式是[%s]", text));
		}
	}

}
